<?php  
  class UploadFile{
    private $max_size   = '2000000'; 
    private $rand_name   = false;   
    private $allow_type  = array();  
    private $error     = 0;     
    private $msg      = '';    
    private $new_name   = '';    
    private $save_path   = '';    
    private $uploaded   = '';    
    private $file     = '';    
    private $file_type   = array();  
    private $file_ext   = '';    
    private $file_name   = '';    
    private $file_size   = 0;     
    private $file_tmp_name = '';    
     
    
    public function __construct($rand_name=false, $save_path='./upload/', $allow_type=''){
      $this->rand_name = $rand_name;
      $this->save_path = $save_path;
      $this->allow_type = $this->get_allow_type($allow_type);
    }
     
    
    public function upload_file($file){
      //$this->file   = $file;
      $this->file_name   = $file['name'];
      $this->file_size   = $file['size'];
      $this->error     = $file['error'];
      $this->file_tmp_name = $file['tmp_name'];
       
      $this->ext = $this->get_file_type($this->file_name);
       
      switch($this->error){
        case 0: $this->msg = ''; break;
        case 1: $this->msg = '超出了php.ini中文件大小'; break;
        case 2: $this->msg = '超出了MAX_FILE_SIZE的文件大小'; break;
        case 3: $this->msg = '文件被部分上传'; break;
        case 4: $this->msg = '没有文件上传'; break;
        case 5: $this->msg = '文件大小为0'; break;
        default: $this->msg = '上传失败'; break;
      }
      if($this->error==0 && is_uploaded_file($this->file_tmp_name)){
        
        if(in_array($this->ext, $this->allow_type)==false){
          $this->msg = '文件类型不正确';
          return false;
        }
        
        if($this->file_size > $this->max_size){
          $this->msg = '文件过大';
          return false;
        }
      }
      $this->set_file_name();
      $this->uploaded = $this->save_path.$this->new_name;
      if(move_uploaded_file($this->file_tmp_name, $this->uploaded)){
        $this->msg = '文件上传成功';
        return true;
      }else{
        $this->msg = '文件上传失败';
        return false;
      }
    }
     
    
    public function set_file_name(){
      if($this->rand_name==false){
        $a = explode(' ', microtime());
        $t = $a[1].($a[0]*1000000);
        $this->new_name = $t.'.'.($this->ext);
      }else{
        $this->new_name = $this->file_name;
      }
    }
     
    
    public function get_file_type($filename){
      $ext = pathinfo($filename, PATHINFO_EXTENSION);
      return $ext;
    }
     
    
    public function get_allow_type($allow_type){
      $s = array();
      if(is_array($allow_type)){
        foreach($allow_type as $value){
          $s[] = $value;
        }
      }else{
        $s = preg_split("/[\s,|;]+/", $allow_type);
      }
      return $s;
    }
     
    //获取错误信息
    public function get_msg(){
      return $this->msg;
    }
  }
?>